﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Noea.Utils;
using System.Xml;
using System.IO;

namespace WebCrawler
{
    public partial class Form1 : Form
    {
		private XmlDocument xmlDoc = null;
		private Stream htmlStream = null;

        public Form1()
        {
            InitializeComponent();
			((ToolStripDropDownMenu)fileMI.DropDown).ShowImageMargin = false;
			((ToolStripDropDownMenu)fileMI.DropDown).ShowCheckMargin = false;
			//((ToolStripDropDownMenu)fileMI.DropDown).AutoSize = false;
			//((ToolStripDropDownMenu)fileMI.DropDown).Width = 110;
        }


        private void Form1_Load(object sender, EventArgs e)
        {
        }


        private void Crawl_Click(object sender, EventArgs e)
        {
			if (urlTextBox.Text.Length == 0)
			{
				MessageBox.Show("Url must be entered!");
				return;
			}
			Crawler crawler = new Crawler(urlTextBox.Text);
			crawler.BuildSiteMap();
			xmlDoc = XmlCreator.getXML(crawler.Sitemap,
				crawler.URL);
			htmlStream = XmlToHtml.convert(xmlDoc);
			htmlStream.Position = 3;
			browser.DocumentStream = htmlStream;
        }

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void saveToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (xmlDoc == null)
			{
				MessageBox.Show("Some page must be crawled first.");
				return;
			}

			SaveFileDialog saveDlg = new SaveFileDialog();
			saveDlg.Title = "Save result as...";
			saveDlg.DefaultExt = "xml";
			saveDlg.Filter = "xml|*.xml|html|*.html";
			if (saveDlg.ShowDialog() == DialogResult.OK)
			{
				string file = saveDlg.FileName;
				if (saveDlg.FilterIndex == 1)
				{
					xmlDoc.Save(file);
					File.Copy("style.xsl", Path.GetDirectoryName(file) + 
						"/style.xsl");
				}
				else
				{
					Stream fileStream = File.Create(saveDlg.FileName);
					htmlStream.Position = 3;
					htmlStream.CopyTo(fileStream);
					fileStream.Close();
				}
			}
		}
           
    }
}
